<?php

namespace App\Service\CommodityService;

use App\Service\BaseService;
use App\Service\Code\Normal;
use Hyperf\Task\Annotation\Task;
use App\Service\InterfaceService\CodeBuilderInterface;

class SkuCodeBuilderService extends BaseService implements CodeBuilderInterface
{
    public $uniqueStr = null;
    
    /**
     * 获取系统生成产生的skucode
     * 
     */
    public function getCode()
    {
        $uniqueStr = $this->getUniqueStr();
    
        //如果毫秒数相同，则休眠一毫秒之后
        if( $this->uniqueStr == $uniqueStr )
        {
            usleep(1000);
            $uniqueStr = $this->getUniqueStr();
        }
    
        //赋值当前skuCode
        $this->uniqueStr = $uniqueStr;
        return $uniqueStr;
    }
    
    /**
     * 获取毫秒级别的日期字符串
     * @return string
     */
    protected function getUniqueStr()
    {
        $parts  = explode(".",microtime(true));
        if (count($parts ) === 2) {
            list($time, $mics) = $parts;
        } else {
            // 处理没有小数部分的情况
            $mics = $parts[0];
        }
        $length = strlen($mics);
        $pos = [
            '1' => '000',
            '2' => '00',
            '3' => '0'
        ];
        $mics = isset($pos[$length]) ? $mics.$pos[$length] : $mics;
        return date('ymdHis').$mics;
    }
}